package com.lily.aidouzixun.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 关于时间的工具类
 */
public class DateUtil {
    /**
     * 日期逻辑，即显示几分钟前，几小时前，昨天
     * @param dateStr
     * @return
     */
    public static String timeLogic(String dateStr) {
        Calendar calendar = Calendar.getInstance();
        calendar.get(Calendar.DAY_OF_MONTH);
        long now = calendar.getTimeInMillis();
        Date date = strToDate(dateStr, "yyyy-MM-dd HH:mm:ss");
        calendar.setTime(date);
        long past = calendar.getTimeInMillis(); //过去的时间
        long time = (now - past) / 1000;    //相差时间
        StringBuffer stringBuffer =  new StringBuffer();
        if (time > 0 && time < 60) {    //一分钟内
            return stringBuffer.append("刚刚").toString();
        } else if(time >= 60 && time < 3600){   //一个小时以内
            return stringBuffer.append((time / 60) + "分钟前").toString();
        } else if (time >= 3600 && time < 24 * 3600) {  //一天以内
            return stringBuffer.append((time / 3600) + "小时前").toString();
        } else if ((time >= 24 * 3600) && (time < 48 * 3600)) {  //两天以内
            return stringBuffer.append("昨天").toString();
        } else if ((time >= 48 * 3600) && (time < 72 * 3600)) {  //三天以内
            return stringBuffer.append("前天").toString();
        }else if ((time >= 72 * 3600) && (time < 360 * 3600)) {  //半个月
            return stringBuffer.append((time / (24 * 3600)) + "天前").toString();
        } else {
            return dateStr.substring(0, 16);
        }
    }

    /**
     * 字符串转日期
     * @return
     */
    public static Date strToDate(String dateStr, String format) {
        Date date = null;
        if (Validator.isEffective(dateStr)) {
            DateFormat dateFormat = new SimpleDateFormat(format);
            try {
                date = dateFormat.parse(dateStr);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return date;
    }
}
